package com.lhj.springboot.web.controller;

import com.alibaba.fastjson2.JSON;
import com.lhj.springboot.web.vo.req.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author lhj
 * @Date 2024/7/6 17:59
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class LoginUserController {

    /**
     * 
     * @param loginVO 请求校验参数
     * @param bindingResult 校验结果 一旦方法上面写了BindingResult 则以我们的BindingResult为准
     * 在请求VO中编写的NotNull注解校验将会失效，校验结果将会自动封装到BindingResult中，我们进行手动处理
     * 如果不想手动处理编写一个全局异常拦截器进行统一处理 
     * @return
     */
    @PostMapping("/login1")
    public ResponseEntity<?> loginUser(@RequestBody @Validated LoginVO loginVO, BindingResult bindingResult) {
        // 是否存在错误
        if (bindingResult.hasErrors()) {
            //1. 自己处理参数错误提示
            Map<String, Object> errorMap = new HashMap<>();
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return ResponseEntity.ok(errorMap);
        }
        log.info("loginVO: {}", JSON.toJSONString(loginVO));  
        return ResponseEntity.ok("success");
    }


    @PostMapping("/login2")
    public ResponseEntity<?> loginUser(@RequestBody @Validated LoginVO loginVO) {
        
        log.info("loginVO: {}", JSON.toJSONString(loginVO));
        return ResponseEntity.ok("success");
    }
}
